package cc.vicp.djx314.starfood.web.order;

import java.util.List;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import cc.vicp.djx314.starfood.domain.dish.Dish;
import cc.vicp.djx314.starfood.domain.order.Order;
import cc.vicp.djx314.starfood.domain.order.OrderDish;
import cc.vicp.djx314.starfood.service.exception.DishNotFoundException;
import cc.vicp.djx314.starfood.service.order.CartService;

@Controller
public class AddAndRemoveDishForOrderController {
	@Autowired
	CartService cartService;

	@RequestMapping(value = "/user/order/adddish/{dishId}", method = RequestMethod.PUT)
	public String dishAddToOrder(@PathVariable("dishId") Integer dishId,
			HttpSession session) throws DishNotFoundException {
		Dish dish = cartService.findDishForCart(dishId);
		Order order = (Order) session.getAttribute("userOrder");
		if (order == null) {
			order = new Order();
			session.setAttribute("userOrder", order);
		}
		List<OrderDish> orderDishes = order.getOrderDishes();
		boolean isExists = false;
		for(OrderDish orderDish : orderDishes) {
			if (dish.getId().equals(orderDish.getDish().getId())) {
				isExists = true;
			}
		}
		if (isExists == false) {
			OrderDish orderDish = new OrderDish(dish);
			orderDishes.add(orderDish);
		}
		return "redirect:/user/cart";
	}

	@RequestMapping(value = "/user/order/removedish/{dishId}", method = RequestMethod.DELETE)
	public String removeDishFromOrder(@PathVariable("dishId") Integer dishId,
			HttpSession session) {
		Order order = (Order) session.getAttribute("userOrder");
		if (order == null) {
			order = new Order();
			session.setAttribute("userOrder", order);
		}
		List<OrderDish> orderDishes = order.getOrderDishes();
		int length = orderDishes.size();
		for(int i = 0; i < length; i++) {
			if (dishId.equals(orderDishes.get(i).getDish().getId())) {
				orderDishes.remove(i);
				break;
			}
		}
		return "redirect:/user/cart";
	}

	@RequestMapping(value = "/user/order/removealldish", method = RequestMethod.DELETE)
	public String removeAllDishFromOrder(HttpSession session) {
		session.removeAttribute("userOrder");
		return "redirect:/user/cart";
	}
}